package com.cc.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cc.dto.CategoryDTO;
import com.cc.model.Category;
import com.cc.mapper.CategoryMapper;
import com.cc.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public Category create(CategoryDTO categoryDTO) {
        Category category = new Category();
        category.setName(categoryDTO.getName());
        category.setDescription(categoryDTO.getDescription());
        category.setCreatedAt(LocalDateTime.now());
        category.setUpdatedAt(LocalDateTime.now());
        categoryMapper.insert(category);
        return category;
    }

    @Override
    public Category update(Long id, CategoryDTO categoryDTO) {
        Category category = categoryMapper.selectById(id);
        if (category != null) {
            category.setName(categoryDTO.getName());
            category.setDescription(categoryDTO.getDescription());
            category.setUpdatedAt(LocalDateTime.now());
            categoryMapper.updateById(category);
        }
        return category;
    }

    @Override
    public void delete(Long id) {
        categoryMapper.deleteById(id);
    }

    @Override
    public Category getById(Long id) {
        return categoryMapper.selectById(id);
    }

    @Override
    public Page<Category> list(int page, int size, String name) {
        // 创建查询条件
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<Category>()
                .like(StringUtils.hasText(name), Category::getName, name)
                .orderByAsc(Category::getName);

        // 返回分页结果
        return categoryMapper.selectPage(new Page<>(page, size), queryWrapper);
    }
}
